<template>
  <a-modal
      v-model:visible="visible"
      :title="title"
      @ok="handleOk"
  >
    <a-form
        ref="formRef"
        :model="formData"
        v-bind="layout"
    >
      <a-form-item name="schoolName" label="学校名称" :rules="[{ required: true, message: '请填写学校名称!' }]">
        <a-input v-model:value="formData.schoolName"/>
      </a-form-item>
      <a-form-item name="bxlx" label="办校类型" :rules="[{ required: true, message: '请选择办校类型!' }]">
        <v-select-dict-item code="BXLX" v-model="formData.bxlx"/>
      </a-form-item>
      <a-form-item name="xxbb" label="学校办别" :rules="[{ required: true, message: '请选择学校办别!' }]">
        <v-select-dict-item code="xxbb" v-model="formData.xxbb"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { reactive, Ref, ref, toRaw } from 'vue'
import { FormInstance, message } from 'ant-design-vue'
import { saveSchool } from '@/api/sys-school'
import VSelectDictItem from '@/components/VSelectDictItem.vue'

const formRef = ref<FormInstance>() as Ref<FormInstance>

const visible = ref(false)
const title = ref('')

const formData = reactive({
  schoolName: '',
  bxlx: '',
  xxbb: ''
})

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 }
}

const open = (data: any) => {
  visible.value = true
  if (data) {
    title.value = '编辑学校'
    Object.assign(formData, data)
  } else {
    title.value = '新增学校'
    Object.keys(formData).forEach(k => {
      formData[k] = ''
    })
  }
}

const emits = defineEmits(['ok'])

const handleOk = async () => {
  await formRef.value.validate()
  await saveSchool(toRaw(formData))
  message.success('操作成功')
  visible.value = false
  emits('ok')
}

defineExpose({ open })
</script>
